import {
  BookInfo,
  Category,
  Borrowing,
  User,
  UserDetail,
} from "../models/model.js";
import { Op } from "sequelize";

// 添加书籍
export async function addBook(bookData) {
  return await BookInfo.create(bookData);
}

// 更新书籍
export async function updateBook(id, bookData) {
  const [updated] = await BookInfo.update(bookData, {
    where: { id },
  });
  if (!updated) throw new Error("Book not found");
  return await BookInfo.findByPk(id);
}

// 删除书籍
export async function deleteBook(id) {
  const deleted = await BookInfo.destroy({ where: { id } });
  if (!deleted) throw new Error("Book not found");
  return deleted;
}

// 书籍查询
export async function getBooks({
  name,
  minPrice,
  maxPrice,
  includeCategory = false,
}) {
  const where = {};
  const include = [];

  if (name) where.name = { [Op.like]: `%${name}%` };

  if (minPrice || maxPrice) {
    where.price = {};
    if (minPrice) where.price[Op.gte] = parseFloat(minPrice);
    if (maxPrice) where.price[Op.lte] = parseFloat(maxPrice);
  }

  if (includeCategory) {
    include.push({
      model: Category,
      as: "category",
      attributes: ["id", "title"],
    });
  }

  return await BookInfo.findAll({ where, include });
}

// 通过ISBN查询
export async function getBookByISBN(isbn) {
  const book = await BookInfo.findOne({ where: { isbn } });
  if (!book) throw new Error("Book not found");
  return book;
}

// 获取书籍详情（含分类信息）
export async function getBookDetails(id) {
  return await BookInfo.findByPk(id, {
    include: [
      {
        model: Category,
        as: "category",
        attributes: ["id", "title"],
      },
    ],
  });
}

export default {
  addBook,
  updateBook,
  deleteBook,
  getBooks,
  getBookByISBN,
  getBookDetails,
};
